package blue.web.dao.service;

import blue.erp.dao.SysOrganizationMapper;
import blue.erp.model.SysOrganization;
import blue.erp.model.SysOrganizationExample;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SysOrganizationService {

    @Autowired
    private SysOrganizationMapper sysOrganizationMapper;


    public int deleteByPrimaryKey(Long id) {

        if(id==null || id<0){
            return 0;
        }
        return sysOrganizationMapper.deleteByPrimaryKey(id);
    }

    public int save(SysOrganization record) {

        if(record==null || StringUtils.isBlank(record.getName())){
            return 0;
        }

        SysOrganizationExample example=new SysOrganizationExample();
        example.createCriteria().andNameEqualTo(record.getName());

        List<SysOrganization> sysUsers=this.select(example);

        if(CollectionUtils.isEmpty(sysUsers)){
            record.setCreateTime(new Date());
            record.setUpdateTime(new Date());
            return sysOrganizationMapper.insert(record);
        }else {
            if(sysUsers.size()==1){
                record.setId(sysUsers.get(0).getId());
                record.setUpdateTime(new Date());
                return sysOrganizationMapper.updateByPrimaryKey(record);
            }
        }

        return 0;
    }


    public List<SysOrganization> select(SysOrganizationExample example) {
        return sysOrganizationMapper.selectByExample(example);
    }

    public SysOrganization selectByPrimaryKey(Long id) {

        if(id==null || id<0){
            return null;
        }

        return sysOrganizationMapper.selectByPrimaryKey(id);
    }

}
